#!/bin/bash
# Function: Start, stop, restart, or check status of a JAR application
# Platform: All Linux Based Platforms
# Version: 1.1
# Date: 2023-03-XX

# Application details
APP_NAME="yudao-server-dev.jar"
DIR_NAME="/home/oa/dev"
JAR_PATH="$DIR_NAME/$APP_NAME"
LOG_FILE="$DIR_NAME/yudao-server-dev.log"

# Usage function
usage() {
    echo "Usage: $0 [start|stop|restart|status]"
    exit 1
}

# Check if the application is running
is_running() {
    pid=$(pgrep -f "$JAR_PATH" | head -n 1)
    if [ -z "$pid" ]; then
        return 1
    else
        return 0
    fi
}

# Start the application
start() {
    if is_running; then
        echo "$APP_NAME is already running. PID=$pid"
    else
        cd "$DIR_NAME"
        nohup java -server -Xms512m -Xmx512m -jar "$JAR_PATH" > "$LOG_FILE" 2>&1 &
        echo "$APP_NAME started successfully"
    fi
}

# Stop the application
stop() {
    if is_running; then
        kill -9 "$pid"
        echo "$APP_NAME stopped"
    else
        echo "$APP_NAME is not running"
    fi
}

# Check the status of the application
status() {
    if is_running; then
        echo "$APP_NAME is running. PID=$pid"
    else
        echo "$APP_NAME is not running"
    fi
}

# Restart the application
restart() {
    stop
    sleep 5
    start
}

# Main logic
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status
        ;;
    restart)
        restart
        ;;
    *)
        usage
        ;;
esac